<template>
  <div>
    <div style="height: 50px; line-height: 50px">
      <el-row>
        <el-col align="right">
          <el-button @click="add">添加</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 弹窗 新增药物 start -->
    <el-dialog title="新增药物" :visible.sync="dialogNewFormVisible" @closed="add_reset">
      <el-form ref="dialogNewForm" :rules="rules_add" :model="type" label-width="80px">
        <el-row>
          <el-col>
            <el-form-item label="适应症" prop="disease">
              <el-select placeholder="请选择" v-model="type.disease">
                <el-option
                  v-for="item in types['diseases']"
                  :key="item.code"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="药物名称" prop="drugName">
              <el-select placeholder="请选择" v-model="type.drugName" filterable>
                <el-option
                  v-for="item in types.drugNames"
                  :key="item.drugCode"
                  :label="item.drugName_label"
                  :value="
                    item.drugName +
                    '@' +
                    item.specs +
                    '@' +
                    item.regulerName +
                    '@' +
                    item.uuid
                  "
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="使用方式" prop="drugMode">
              <el-select placeholder="请选择" v-model="type.drugMode">
                <el-option
                  v-for="item in types.drugModes"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="剂型" prop="unit">
              <el-select placeholder="请选择" v-model="type.unit">
                <el-option
                  v-for="item in types.units"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">频次</el-divider>

        <div class="frequencyBox">
          <ul class="frequencyList">
            <li v-for="(item, index) in type.frequency['a']" :key="item.id">
              <div class="title" v-if="index == 0" @click="add_choice('a')">{{ item.name }}</div>
              <div class="title" v-else>{{ item.name }}</div>
              <div class="spec">
                <div class="text">{{ item.num }}</div>
                <div class="unit">{{ type.unit }}</div>
              </div>
            </li>
          </ul>

          <ul class="frequencyList">
            <li v-for="(item, index) in type.frequency['b']" :key="item.id">
              <div class="title" v-if="index == 0" @click="add_choice('b')">{{ item.name }}</div>
              <div class="title" v-else>{{ item.name }}</div>
              <div class="spec">
                <div class="text">{{ item.num }}</div>
                <div class="unit">{{ type.unit }}</div>
              </div>
            </li>
          </ul>

          <ul class="frequencyList">
            <li v-for="(item, index) in type.frequency['c']" :key="item.id">
              <div class="title" v-if="index == 0" @click="add_choice('c')">{{ item.name }}</div>
              <div class="title" v-else>{{ item.name }}</div>
              <div class="spec">
                <div class="text">{{ item.num }}</div>
                <div class="unit">{{ type.unit }}</div>
              </div>
            </li>
          </ul>
        </div>

        <div style="text-align:center">
          <el-button @click="dialogNewFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onNewSubmit('dialogNewForm')">保存</el-button>
        </div>
      </el-form>

      <el-dialog
        width="30%"
        title="请选择频次"
        :visible.sync="dialogNewForm_innerVisible"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :show-close="false"
        append-to-body
      >
        <el-form ref="dialogNewForm" :model="types.frequencies">
          <div class="frequenciesBox">
            <ul class="frequencyList">
              <li v-for="(item,index) in types.frequencies_cur" :key="index">
                <div class="title">{{ item.name }}</div>
                <div class="spec">
                  <div class="text">
                    <el-input
                      :data-item_name="'p'+index"
                      v-model="item.num"
                      autocomplete="off"
                      size="mini"
                      type="number"
                      @blur.native.capture="limitPositiveInteger"
                    ></el-input>
                  </div>
                  <div class="unit">{{ type.unit }}</div>
                </div>
              </li>
            </ul>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onNewInsideSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
    <!-- 弹窗 新增药物 end -->

    <!-- 弹窗 用药干预 start -->
    <el-dialog title="用药干预" :visible.sync="dialogEditFormVisible" @closed="edit_reset">
      <el-form ref="dialogEditForm" :model="type_edit" :rules="rules_edit" label-width="80px">
        <el-row>
          <el-col>
            <el-form-item label="适应症" prop="disease">
              <el-select placeholder="请选择" v-model="type_edit.disease">
                <el-option
                  v-for="item in types['diseases']"
                  :key="item.code"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="药物名称" prop="drugName">
              <el-select placeholder="请选择" v-model="type_edit.drugName" filterable>
                <el-option
                  v-for="item in types.drugNames"
                  :key="item.drugCode"
                  :label="item.drugName_label"
                  :value="
                    item.drugName +
                    '@' +
                    item.specs +
                    '@' +
                    item.regulerName +
                    '@' +
                    item.uuid
                  "
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="使用方式" prop="drugMode">
              <el-select placeholder="请选择" v-model="type_edit.drugMode">
                <el-option
                  v-for="item in types.drugModes"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="剂型" prop="unit">
              <el-select placeholder="请选择" v-model="type_edit.unit">
                <el-option
                  v-for="item in types.units"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">频次</el-divider>

        <div class="frequencyBox">
          <ul class="frequencyList">
            <li v-for="(item, index) in type_edit.frequency['a']" :key="item.id">
              <div class="title" v-if="index == 0" @click="edit_choice('a')">{{ item.name }}</div>
              <div class="title" v-else>{{ item.name }}</div>
              <div class="spec">
                <div class="text">{{ item.num }}</div>
                <div class="unit">{{ type_edit.unit }}</div>
              </div>
            </li>
          </ul>

          <ul class="frequencyList">
            <li v-for="(item, index) in type_edit.frequency['b']" :key="item.id">
              <div class="title" v-if="index == 0" @click="edit_choice('b')">{{ item.name }}</div>
              <div class="title" v-else>{{ item.name }}</div>
              <div class="spec">
                <div class="text">{{ item.num }}</div>
                <div class="unit">{{ type_edit.unit }}</div>
              </div>
            </li>
          </ul>

          <ul class="frequencyList">
            <li v-for="(item, index) in type_edit.frequency['c']" :key="item.id">
              <div class="title" v-if="index == 0" @click="edit_choice('c')">{{ item.name }}</div>
              <div class="title" v-else>{{ item.name }}</div>
              <div class="spec">
                <div class="text">{{ item.num }}</div>
                <div class="unit">{{ type_edit.unit }}</div>
              </div>
            </li>
          </ul>
        </div>

        <el-divider content-position="left">干预</el-divider>

        <el-row>
          <el-col :span="12">
            <el-form-item label="干预分类" prop="ajustment_question">
              <el-select
                placeholder="请选择"
                v-model="type_edit.ajustment_question"
                @change="get_ajustment_reason"
              >
                <el-option
                  v-for="(item,index) in types.ajustments_questions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="干预原因" prop="ajustment_reason">
              <el-select placeholder="请选择" v-model="type_edit.ajustment_reason">
                <el-option
                  v-for="(item,index) in types.ajustments_reasons"
                  :key="index"
                  :label="item.reason"
                  :value="item.reason"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="type_edit.mark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="text-align:center">
          <el-button @click="dialogEditFormVisible = false">取消</el-button>
          <el-button
            v-if="isJustOnlyEdit"
            type="primary"
            @click="onEditOnlySubmit('dialogEditForm')"
          >保存</el-button>
          <el-button v-else type="primary" @click="onStopAndAddSubmit('dialogEditForm')">保存</el-button>
        </div>
      </el-form>

      <el-dialog
        width="30%"
        title="请选择频次"
        :visible.sync="dialogEditForm_innerVisible"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :show-close="false"
        append-to-body
      >
        <el-form :model="types.frequencies">
          <div class="frequenciesBox">
            <ul class="frequencyList">
              <li v-for="(item,index) in types.frequencies_cur" :key="index">
                <div class="title">{{ item.name }}</div>
                <div class="spec">
                  <div class="text">
                    <el-input
                      :data-item_name="'p'+index"
                      v-model="item.num"
                      autocomplete="off"
                      size="mini"
                      type="number"
                      @blur.native.capture="limitPositiveInteger"
                    ></el-input>
                  </div>
                  <div class="unit">{{ type_edit.unit }}</div>
                </div>
              </li>
            </ul>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onEditInsideSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
    <!-- 弹窗 用药干预 end -->

    <!-- 弹窗 停药干预 start -->
    <el-dialog title="停药干预" :visible.sync="dialogStopFormVisible" @closed="stop_reset">
      <el-form ref="dialogStopForm" :model="type_stop" :rules="rules_stop" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="干预分类" prop="ajustment_question">
              <el-select
                placeholder="请选择"
                v-model="type_stop.ajustment_question"
                @change="get_ajustment_reason"
              >
                <el-option
                  v-for="(item,index) in types.ajustments_questions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="干预原因" prop="ajustment_reason">
              <el-select placeholder="请选择" v-model="type_stop.ajustment_reason">
                <el-option
                  v-for="(item,index) in types.ajustments_reasons"
                  :key="index"
                  :label="item.reason"
                  :value="item.reason"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="type_stop.mark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button @click="dialogStopFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onStopSubmit('dialogStopForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 弹窗 停药干预 end -->

    <el-table
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column prop="disease" label="适应症"></el-table-column>

      <el-table-column prop="commonName" label="通用名"></el-table-column>

      <el-table-column prop="itemName" label="商品名"></el-table-column>

      <el-table-column prop="spec" label="规格"></el-table-column>

      <el-table-column prop="drugMode" label="用法用量"></el-table-column>

      <el-table-column prop="startTime" label="开始用药时间"></el-table-column>

      <el-table-column prop="stopTime" label="结束用药时间"></el-table-column>

      <el-table-column prop="stopAsk" label="干预分类">
        <template slot-scope="scope">{{intervention(scope.row)}}</template>
      </el-table-column>

      <!-- <el-table-column prop="mark" label="备注"> </el-table-column> -->

      <el-table-column prop="operation" label="操作" width="100">
        <template slot-scope="scope" v-if="typeof scope.row.stopTime != 'string'">
          <el-button @click="edit(scope.row)" type="text" size="small">干预</el-button>
          <el-button type="text" size="small" @click="stop(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      align="center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[1, 5, 10, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.length"
    />
  </div>
</template>

<script>
import {
  getList,
  getItem,
  queryItem,
  queryFrequencies,
  queryDiseases,
  addDrug,
  getAdjustment,
  editDrug,
  stopDrug
} from "@/api/follow-up/follow-up-details";
import {
  frequencies,
  type_init,
  type_edit_init,
  type_stop_init
} from "@/assets/data/the-medical-information";

import { echodisplays } from "@/api/follow-up/follow-up-records"; // 值域接口

/**
 * 数据-新增药物 初始
 */
export default {
  props: ["patId"],
  data() {
    return {
      type_stop: JSON.parse(JSON.stringify(type_stop_init)),
      type_edit: JSON.parse(JSON.stringify(type_edit_init)),
      type: JSON.parse(JSON.stringify(type_init)),
      types: {
        diseases: [], //适应症
        drugModes: [], //使用方式
        units: [], //剂型
        drugNames: [], //药物名称
        specs: [], //规格
        frequencies: JSON.parse(JSON.stringify(frequencies)), //频次
        frequencies_cur: [],
        ajustments_questions: [], //干预分类
        ajustments_reasons: [], //干预原因
        ajustments: [] //干预集合
      },
      patientId: "", //20200508175357228
      type_edit_medicineNameNew: "",
      tableData: [], // 历史用药信息
      currentPage: 1, // 初始页
      pageSize: 5, // 每页的数据
      choice_sort: "a",
      justOnlyEdit: {}, //用药干预相关
      isJustOnlyEdit: true, //用药干预相关
      isValidNumber: [], //频次是不是正整数或零
      dialogNewFormVisible: false,
      dialogNewForm_innerVisible: false,
      dialogEditFormVisible: false,
      dialogEditForm_innerVisible: false,
      dialogStopFormVisible: false,
      rules_add: {
        disease: [{ required: true, message: "请选择", trigger: "change" }],
        drugName: [{ required: true, message: "请选择", trigger: "change" }],
        drugMode: [{ required: true, message: "请选择", trigger: "change" }],
        unit: [{ required: true, message: "请选择", trigger: "change" }]
      },
      rules_edit: {
        ajustment_question: [
          { required: true, message: "请选择", trigger: "change" }
        ],
        ajustment_reason: [
          { required: true, message: "请选择", trigger: "change" }
        ]
      },
      rules_stop: {
        ajustment_question: [
          { required: true, message: "请选择", trigger: "change" }
        ],
        ajustment_reason: [
          { required: true, message: "请选择", trigger: "change" }
        ]
      }
    };
  },
  watch: {
    type_edit: {
      // 表示对象中属性变化的处理函数，这个函数只能叫这个名字
      handler(newVal) {
        let res = {};
        res.disease = newVal.disease;
        res.drugName = newVal.drugName;
        res.drugMode = newVal.drugMode;
        res.unit = newVal.unit;
        res.frequency = newVal.frequency;
        let _res = JSON.stringify(res);
        let _justOnlyEdit = JSON.stringify(this.justOnlyEdit);

        if (_res == _justOnlyEdit) {
          this.isJustOnlyEdit = true;
        } else {
          this.isJustOnlyEdit = false;
        }
      },
      immediate: false, // 代表在wacth里声明了 user这个方法之后立即先去执行handler方法
      deep: true // 表示开启深度监听
    }
  },
  computed: {
    /**
     * 筛选频次
     */
    frequencies_pure() {
      let that = this;

      return function(sort) {
        let result = that.types.frequencies[sort].filter((item, index) => {
          return item.num > 0;
        });

        return result;
      };
    },

    /**
     * 删除-停药干预 干预分类|干预原因|备注
     */
    stopAsk() {
      let stopAsk =
        this.type_stop.ajustment_question +
        "|" +
        this.type_stop.ajustment_reason;
      let mark = this.trim(this.type_stop.mark);

      if (mark !== "") {
        stopAsk += "|" + this.type_stop.mark;
      }

      return stopAsk;
    }
  },
  filters: {},
  methods: {
    intervention(row) {
      let r = "",
        ask1 = "",
        ask2 = "";

      if (row.stopAsk != "") {
        ask1 = this.stopAskFormat(row.stopAsk);
      }

      if (row.mark != "") {
        ask2 = this.stopAskFromMark(row.mark);
      }

      if (ask1 != "" && ask2 != "") {
        r = ask1 + " | " + ask2;
      } else {
        r = ask1 + ask2;
      }

      return r;
    },
    stopAskFormat(str) {
      //ask1
      let _type = typeof str;
      let _res = "";
      if (_type !== "undefined") {
        _res = str.split("|")[0];
      } else {
        _res = "";
      }
      return _res;
    },
    stopAskFromMark(str) {
      //ask2
      let result = "";
      if (typeof str === "string") {
        result = str.split("|")[3];
      }
      return result;
    },
    /**
     * 限制只能输入正整数
     */
    limitPositiveInteger(e) {
      let _val = e.target.value;
      let _itemName = e.target.dataset.item_name;

      let _bool = /^(0|[1-9][0-9]*)$/.test(_val);
      if (!_bool) {
        e.target.style.borderColor = "#ff4949";
        this.isValidNumber.push(_itemName);
      } else {
        e.target.style.borderColor = "#DCDFE6";
        this.isValidNumber = this.isValidNumber.filter(
          item => item != _itemName
        );
      }
    },
    /**
     * 去掉字符串两端空格
     */
    trim(str) {
      let res = str.replace(/(^\s*)|(\s*$)/g, "");

      return res;
    },

    /**
     * 获取当前日期时间
     * 格式:yyyy-MM-dd HH:mm:ss
     */
    getNowFormatDateTime() {
      var date = new Date();
      var seperator1 = "-";
      var seperator2 = ":";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      var strHour = date.getHours();
      var strMinutes = date.getMinutes();
      var strSeconds = date.getSeconds();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      if (strHour >= 0 && strHour <= 9) {
        strHour = "0" + strHour;
      }
      if (strMinutes >= 0 && strMinutes <= 9) {
        strMinutes = "0" + strMinutes;
      }
      if (strSeconds >= 0 && strSeconds <= 9) {
        strSeconds = "0" + strSeconds;
      }
      var currentdatetime =
        year +
        seperator1 +
        month +
        seperator1 +
        strDate +
        " " +
        strHour +
        seperator2 +
        strMinutes +
        seperator2 +
        strSeconds;
      return currentdatetime;
    },

    /**
     * 转化频次数据格式为字符串
     */
    convert_frequency(frequency) {
      let res = [];
      let str = "";

      Object.values(frequency).forEach((item, index) => {
        res.push(item.filter(obj => obj.num > 0));
      });

      res = [].concat(...res); //数组降维

      res.forEach(item => {
        str += item.num + "|" + item.name + ",";
      });

      str = str.slice(0, str.length - 1);

      return str;
    },

    /**
     * 转化频次字符串为对象
     */
    frequency_str2obj(medicineNameNew) {
      let _frequencies = this.types.frequencies;
      let str = medicineNameNew;
      let arr = [];
      let arr_filter = [];
      let _obj = {};

      arr = str.split(",");

      arr.forEach(item => {
        arr_filter.push({
          name: item.split("|")[1],
          num: item.split("|")[0]
        });
      });

      for (let [sort, items] of Object.entries(_frequencies)) {
        _obj[sort] = [];

        arr_filter.forEach((item, index) => {
          _frequencies[sort].forEach(item1 => {
            if (item.name == item1.name) {
              item.id = item1.id;
              _obj[sort].push(item);
            }
          });
        });
      }

      return _obj;
    },

    /**
     * 获取 patientId
     */
    getPatientId() {
      let _id = this.$route.query.patId || this.patId;
      return _id;
    },

    /**
     * 新增
     */
    add() {
      this.dialogNewFormVisible = true;
    },

    add_choice(sort) {
      this.choice_sort = sort;
      this.types.frequencies_cur = this.types.frequencies[sort];
      this.dialogNewForm_innerVisible = true;
    },

    onNewInsideSubmit() {
      if (this.isValidNumber.length > 0) {
        this.$message.error("输入数据有误");
        return;
      }
      let sort = this.choice_sort;
      let pure = this.frequencies_pure(sort);

      if (sort == "b") {
        if (pure.length > 1) {
          this.$message.error("只可填写其中一项");
          return;
        }
      }

      if (pure.length > 0) {
        this.type.frequency[sort] = pure;
      }
      this.dialogNewForm_innerVisible = false;
    },

    onNewSubmit(formName) {
      let that = this;
      let flag = false;
      let drugNames = this.type.drugName.split("@"); //[drugName,specs,regulerName,uuid]

      this.$refs[formName].validate(valid => {
        if (valid) {
          flag = true;
          console.log("submit");
        } else {
          flag = false;
          console.log("error submit!!");
          return false;
        }
      });

      if (!flag) {
        return;
      }

      if (that.convert_frequency(that.type.frequency) == "") {
        this.$message({
          message: "请录入频次信息",
          type: "error"
        });
        return;
      }

      const b = [
        {
          amount: -1, //写死
          commonName: drugNames[2], //药品regulerName
          disease: that.type.disease, //disease
          drugMode: that.type.drugMode, //drugMode
          itemCode: drugNames[3], //药品uuid
          itemName: drugNames[0], //drugName
          medicineNameNew: that.convert_frequency(that.type.frequency), //frequency
          orderType: "0", //写死
          patientId: this.patientId, //20200508175357228
          single: -1, //写死
          spec: drugNames[1], //spec
          startTime: that.getNowFormatDateTime(), //获取当前时间
          toldTime: that.getNowFormatDateTime(), //获取当前时间
          tolddoctorId: this.$store.getters.userId, //管理员id
          tolddoctorName: this.$store.getters.name, //管理员
          unit: that.type.unit //unit
        }
      ];

      addDrug(b).then(res => {
        let result = res;
        this.$message({
          message: "操作成功",
          type: "success"
        });
        this.getTableData();
      });

      this.dialogNewFormVisible = false;
    },

    /**
     * 新增药物 数据初始化
     */
    add_reset() {
      let frequencies_reset = JSON.parse(JSON.stringify(frequencies));
      let type_reset = JSON.parse(JSON.stringify(type_init));

      this.type = type_reset;
      this.$refs["dialogNewForm"].resetFields();
      this.types.frequencies = frequencies_reset;
      this.isValidNumber = [];
    },

    /**
     * 修改用药 用药干预 数据初始化
     */
    edit_reset() {
      let type_edit_reset = JSON.parse(JSON.stringify(type_edit_init));
      let frequencies_reset = JSON.parse(JSON.stringify(frequencies));

      this.type_edit = type_edit_reset;
      this.types.frequencies = frequencies_reset;

      this.$refs["dialogEditForm"].resetFields();

      this.isJustOnlyEdit = true;
      this.isValidNumber = [];
    },

    /**
     * 修改用药 用药干预
     */
    edit(row) {
      //console.log(row);
      let item = this.type_edit;
      let _frequency = JSON.parse(JSON.stringify(type_edit_init.frequency));
      let _frequencies = JSON.parse(JSON.stringify(frequencies));
      let _medicineNameNew = this.frequency_str2obj(row.medicineNameNew);
      let _justOnlyEdit = this.justOnlyEdit;
      this.type_edit_medicineNameNew = this.frequency_str2obj(
        row.medicineNameNew
      );

      item.uuid = row.uuid;
      item.wrongOper = row.wrongOper;
      item.disease = row.disease; //适应症
      item.drugName = row.itemName; //药物名称
      item.commonName = row.commonName;
      item.drugMode = row.drugMode; //使用方式
      item.unit = row.unit; //剂型
      item.spec = row.spec; //规格

      item.frequency.a = Object.assign(_frequency.a, _medicineNameNew.a); //频次
      item.frequency.b = Object.assign(_frequency.b, _medicineNameNew.b);
      item.frequency.c = Object.assign(_frequency.c, _medicineNameNew.c);
      this.types._frequencies = _frequencies;
      this.types.frequencies.a = Object.assign(
        _frequencies.a,
        _medicineNameNew.a
      );
      this.types.frequencies.b = Object.assign(
        _frequencies.b,
        _medicineNameNew.b
      );
      this.types.frequencies.c = Object.assign(
        _frequencies.c,
        _medicineNameNew.c
      );

      /** 用药干预 */
      _justOnlyEdit.disease = row.disease; //适应症
      _justOnlyEdit.drugName = row.itemName; //药物名称
      _justOnlyEdit.drugMode = row.drugMode; //使用方式
      _justOnlyEdit.unit = row.unit; //剂型
      _justOnlyEdit.frequency = {};
      _justOnlyEdit.frequency.a = Object.assign(
        _frequency.a,
        _medicineNameNew.a
      ); //频次
      _justOnlyEdit.frequency.b = Object.assign(
        _frequency.b,
        _medicineNameNew.b
      );
      _justOnlyEdit.frequency.c = Object.assign(
        _frequency.c,
        _medicineNameNew.c
      );

      this.dialogEditFormVisible = true;
    },

    edit_choice(sort) {
      this.choice_sort = sort;
      this.types.frequencies_cur = this.types.frequencies[sort];
      this.dialogEditForm_innerVisible = true;
    },

    onEditInsideSubmit() {
      let that = this;
      let sort = this.choice_sort;
      let pure = this.frequencies_pure(sort);
      let _state_init = this.convert_frequency(this.type_edit_medicineNameNew);

      if (sort == "b") {
        if (pure.length > 1) {
          this.$message.error("只可填写其中一项");
          return;
        }
      }

      if (pure.length > 0) {
        this.type_edit.frequency[sort] = pure;
      }

      let _change = JSON.stringify(this.type.frequency);

      if (_state_init !== this.convert_frequency(this.type_edit.frequency)) {
        this.$nextTick(function() {
          that.isJustOnlyEdit = false;
        });
      } else {
        this.$nextTick(function() {
          that.isJustOnlyEdit = true;
        });
      }

      this.dialogEditForm_innerVisible = false;
    },

    /**
     * 修改 干预但不修改剂量
     */
    onEditOnlySubmit(formName) {
      let that = this;
      let flag = false;
      let item = this.type_edit;

      this.$refs[formName].validate(valid => {
        if (valid) {
          flag = true;
          console.log("submit");
        } else {
          flag = false;
          console.log("error submit!!");
          return false;
        }
      });

      if (!flag) {
        return;
      }

      let mark =
        this.$store.getters.userId +
        "|" +
        this.$store.getters.name +
        "|" +
        this.getNowFormatDateTime() +
        "|" +
        item.ajustment_question +
        "|" +
        item.ajustment_reason;

      if (this.trim(item.mark) !== "") {
        mark += "|" + item.mark;
      }

      let b = {
        uuid: item.uuid,
        mark: mark
      };

      editDrug(b).then(result => {
        this.$message({
          message: "操作成功",
          type: "success"
        });

        this.getTableData();
      });
      this.dialogEditFormVisible = false;
    },

    /**
     * 停用并新增 干预修改剂量（ 先停用， 再新增）
     */
    onStopAndAddSubmit(formName) {
      let that = this;
      let flag = false;
      let item = this.type_edit;
      let _frequency = this.convert_frequency(this.type_edit.frequency);

      this.$refs[formName].validate(valid => {
        if (valid) {
          flag = true;
        } else {
          flag = false;

          return false;
        }
      });

      if (!flag) {
        return;
      }

      if (_frequency == "") {
        this.$message({
          message: "请录入频次信息",
          type: "error"
        });
        return;
      }

      let stopAsk = item.ajustment_question + "|" + item.ajustment_question;
      let mark = this.trim(item.mark);

      if (this.trim(item.mark) !== "") {
        mark += "|" + item.mark;
      }

      let b_stop = {
        uuid: item.uuid,
        adviceState: "3", //写死
        wrongOper: item.wrongOper,
        stopdoctorId: this.$store.getters.userId,
        stopdoctorName: this.$store.getters.name,
        stopTime: this.getNowFormatDateTime(), //获取 当前时间
        stopAsk: stopAsk //干预分类|干预原因|备注
      };

      let b_add = [
        {
          amount: -1, //写死
          commonName: item.commonName,
          disease: item.disease,
          drugMode: item.drugMode,
          itemCode: item.uuid, //药品uuid
          itemName: item.drugName, //drugName
          medicineNameNew: that.convert_frequency(that.type_edit.frequency), //frequency "1|晨起后,2|Tid(餐前)"
          orderType: "0", //写死
          patientId: this.patientId,
          single: -1, //写死
          spec: item.spec, //spec
          startTime: this.getNowFormatDateTime(), //获取当前时间
          toldTime: this.getNowFormatDateTime(), //获取当前时间
          tolddoctorId: this.$store.getters.userId, //登录人id
          tolddoctorName: this.$store.getters.name, //登录人
          unit: item.unit
        }
      ];

      //停用
      stopDrug(b_stop).then(res => {
        let result = res;

        //新增
        addDrug(b_add).then(res => {
          let result = res;
          this.$message({
            message: "操作成功",
            type: "success"
          });
          this.getTableData();
        });
      });

      this.dialogEditFormVisible = false;
    },

    /**
     * 删除 停用
     */
    stop(row) {
      let item = this["type_stop"];

      item.uuid = row.uuid;
      item.adviceState = row.adviceState;
      item.wrongOper = row.wrongOper;
      item.stopdoctorId = this.$store.getters.userId;
      item.stopdoctorName = this.$store.getters.name;

      this.dialogStopFormVisible = true;
    },

    /**
     * 停用 reset
     */
    stop_reset() {
      this.$refs["dialogStopForm"].resetFields();
    },

    onStopSubmit(formName) {
      if (this.isValidNumber.length > 0) {
        this.$message.error("输入数据有误");
        return;
      }

      let that = this;
      let flag = false;
      let item = this["type_stop"];

      this.$refs[formName].validate(valid => {
        if (valid) {
          flag = true;
          console.log("submit");
        } else {
          flag = false;
          console.log("error submit!!");
          return false;
        }
      });

      if (!flag) {
        return;
      }

      let b = {
        uuid: item.uuid, //获取
        adviceState: item.adviceState, //获取
        wrongOper: item.wrongOper, //获取
        stopdoctorId: item.stopdoctorId, //获取
        stopdoctorName: item.stopdoctorName, //获取
        stopTime: this.getNowFormatDateTime(), //获取 当前时间
        stopAsk: this.stopAsk //干预分类|干预原因|备注
      };

      stopDrug(b).then(res => {
        let result = res;
        this.$message({
          message: "操作成功",
          type: "success"
        });
        that.dialogStopFormVisible = false;
        that.getTableData();
      });
    },

    /**
     * 获取干预分类的对应干预原因
     */
    get_ajustment_reason(question) {
      let res = this.types.ajustments.filter(
        item => item.question === question
      );
      this.types.ajustments_reasons = res;
    },

    /**
     * 历史用药信息
     */
    getTableData() {
      let that = this;
      const b = {
        patientId: this.patientId
      };

      getList(b).then(res => {
        let result = res;
        that.tableData = result;
      });
    },

    /**
     * 使用方式列表
     */
    getDrugMode() {
      let that = this;
      let arr = [];

      const b = {
        parent_type: "USEKIND"
      };

      getItem(b).then(res => {
        let result = res;

        result.forEach((item, index) => {
          arr.push({
            id: item.id,
            name: item.name
          });
        });

        that.types["drugModes"] = arr;
      });
    },

    /**
     * 剂型列表
     */
    getSpecs() {
      let that = this;
      let arr = [];

      const b = {
        parent_type: "PHA_DOSE_MODEL"
      };

      getItem(b).then(res => {
        let result = res;

        result.forEach((item, index) => {
          arr.push({
            id: item.id,
            name: item.name
          });
        });

        that.types["units"] = arr;
      });
    },

    /**
     * 药物名称列表
     */
    getNames() {
      let that = this;
      let arr = [];

      const b = {
        token: this.$store.getters.token
      };

      queryItem(b).then(res => {
        let result = res;
        result.forEach((item, index) => {
          arr.push({
            uuid: item.uuid,
            drugCode: item.drugCode,
            regulerName: item.regulerName,
            drugName: item.drugName,
            specs: item.specs,
            drugName_label: item.drugName + "(" + item.specs + ")"
          });
        });
        that.types.drugNames = arr;
      });
    },

    /**
     * 适应症列表
     */
    async getDiseases() {
      let diseases = [];

      const a = {
        id:this.patientId
      }

      const b = {
        rangeCode: "disease_info"
      };

      await echodisplays(a).then(res => {
        let result = res.data;
        diseases = result.memDiseaseInfoCodes.split(',');
      })


      queryDiseases(b).then(res => {
        let result = res.data;
        let _result = [];

        result.reduce((current,next) => {
          if(diseases.includes(next.code)){
            _result.push(next);
          }
        },[])

        this.types["diseases"] = _result;
      });
    },

    /**
     * 干预分类 vs 干预原因
     */
    getAdjustment() {
      let that = this;
      let arr = [];

      const b = {
        token: this.$store.getters.token
      };

      getAdjustment(b).then(res => {
        let result = res;
        let questions = [];

        result.forEach(item => {
          if (!questions.includes(item.question)) {
            questions.push(item.question);
          }
        });

        that.types.ajustments_questions = questions;
        that.types.ajustments = result;
      });
    },

    getAllItems() {
      this.getNames();
      this.getDrugMode();
      this.getSpecs();
      this.getDiseases();
      this.getAdjustment();
    },

    handleSizeChange(val) {
      //console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      //console.log(`当前页: ${val}`);
      this.currentPage = val;
    }
  },
  created: function() {
    this.patientId = this.getPatientId();
  },
  mounted: function() {
    this.getTableData();
    this.getAllItems();
  }
};
</script>

<style lang="scss" scoped>
.frequencyBox {
  margin-bottom: 20px;
  .frequencyList {
    display: block;
    margin: 0;
    padding: 0;
    list-style: none;
    line-height: 36px;

    li {
      display: flex;
      margin: 0;
      padding: 0;
      justify-content: space-between;
      border-bottom: 1px solid #dcdfe6;
      &:first-child:not(.stop) {
        cursor: pointer;
        .title {
          font-family: "element-icons" !important;
          font-style: normal;
          font-weight: normal;
          font-variant: normal;
          text-transform: none;
          line-height: 1;
          vertical-align: baseline;
          display: inline-block;
          -webkit-font-smoothing: antialiased;
          -moz-osx-font-smoothing: grayscale;
          line-height: 36px;

          &::after {
            content: "\e6e0";
          }
        }
      }
      .spec {
        display: flex;
        justify-content: space-between;
        .el-input {
          width: 100px;
        }
        .unit {
          padding-left: 15px;
        }
      }
    }
  }
}
.frequenciesBox {
  margin-bottom: 20px;
  .frequencyList {
    display: block;
    margin: 0;
    padding: 0;
    list-style: none;
    line-height: 36px;

    li {
      display: flex;
      margin: 0;
      padding: 0;
      justify-content: space-between;
      border-bottom: 1px solid #dcdfe6;
      .spec {
        display: flex;
        justify-content: space-between;
        .el-input {
          width: 100px;
        }
        .unit {
          padding-left: 15px;
        }
      }
    }
  }
}
</style>